package com.easylinkin.linkappapi.safe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.service.AppSendMessageService;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.common.utils.message.entity.AppSendMessage.model;
import com.easylinkin.linkappapi.common.utils.message.entity.AppSendMessage.type;
import com.easylinkin.linkappapi.messagecenter.entity.MessageCenter;
import com.easylinkin.linkappapi.messagecenter.entity.enumType.messageTypeEnum;
import com.easylinkin.linkappapi.messagecenter.service.MessageCenterService;
import com.easylinkin.linkappapi.safe.dao.HiddenDangerInfoMapper;
import com.easylinkin.linkappapi.safe.dao.HiddenDangerMapper;
import com.easylinkin.linkappapi.safe.dto.HiddenDangerDTO;
import com.easylinkin.linkappapi.safe.entity.HiddenDanger;
import com.easylinkin.linkappapi.safe.entity.HiddenDangerInfo;
import com.easylinkin.linkappapi.safe.entity.vo.HiddenDangerInfoVo;
import com.easylinkin.linkappapi.safe.service.HiddenDangerInfoService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * HiddenDangerInfo表服务实现类
 *
 * @author CodeGenerator
 * @date 2022/07/21
 */
@Slf4j
@Service("appHiddenDangerInfoService")
public class HiddenDangerInfoServiceImpl extends ServiceImpl<HiddenDangerInfoMapper, HiddenDangerInfo>
		implements HiddenDangerInfoService {
	@Resource
	private CommonService commonService;
	@Resource
	private LinkappUserContextProducer linkappUserContextProducer;

	@Autowired
	private HiddenDangerMapper hiddenDangerMapper;

	@Autowired
	private MessageCenterService messageCenterService;

	@Autowired
	private AppSendMessageService appSendMessageService;

	@Override
	public boolean saveOne(HiddenDangerInfo appHiddenDangerInfo) {

		// 校验参数
		validParamRequired(appHiddenDangerInfo);

		HiddenDanger hiddenDanger = hiddenDangerMapper.selectById(appHiddenDangerInfo.getCheckAccountId());

		if (hiddenDanger == null || hiddenDanger.getStatus() == 2) {

			throw new BusinessException("操作失败,记录异常");
		}

		boolean flag = false;

		if (hiddenDanger.getStatus() == 0) {

			if (!linkappUserContextProducer.getCurrent().getId().equals(hiddenDanger.getRectifyUid())) {

				throw new BusinessException("您不是当前记录整改人!");
			}

			// 待整改状态 往info表插入数据
			appHiddenDangerInfo.setIsEnd(0);
			appHiddenDangerInfo.setRectifyTime(new Date());

			flag = save(appHiddenDangerInfo);

			// 修改隐患记录状态为待复查
			hiddenDanger.setStatus(1);

			// 给复查人发送复查消息
			saveMessage("隐患复查提醒", "您有一条待复查隐患记录，请尽快处理!", String.valueOf(hiddenDanger.getCheckUid()),
					hiddenDanger.getId(),true);

		} else if (hiddenDanger.getStatus() == 1) {
			// 复查提交

			if (!linkappUserContextProducer.getCurrent().getId().equals(hiddenDanger.getCheckUid())) {

				throw new BusinessException("您不是当前记录复查人!");
			}

			if (appHiddenDangerInfo.getCheckResult() == 1) {

				// 复查通过
				hiddenDanger.setStatus(2);// 已合格
				hiddenDanger.setCloseTime(new Date());

				// 复查通过，给检查人发送消息提醒
				saveMessage("隐患复查通过", "您发布的隐患记录已经复查通过!", String.valueOf(hiddenDanger.getCreateUid()),
						hiddenDanger.getId(),true);
			} else {
				// 复查不通过，重置hiddenDanger表记录状态为待整改，设置此条整改记录为历史记录
				hiddenDanger.setStatus(0);

				// 给待整改人发送消息提醒
				saveMessage("隐患整改提醒", "复查未通过，您有一条待整改隐患记录，请尽快处理!", String.valueOf(hiddenDanger.getRectifyUid()),
						hiddenDanger.getId(),true);
			}

			appHiddenDangerInfo.setIsEnd(1);
			appHiddenDangerInfo.setCheckTime(new Date());

			flag = updateById(appHiddenDangerInfo);

		}

		// 修改隐患记录状态
		hiddenDangerMapper.updateById(hiddenDanger);

		return flag;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateOne(HiddenDangerInfo appHiddenDangerInfo) {
		Assert.notNull(appHiddenDangerInfo.getId(), "id不能为空");
		commonService.setModifyInfo(appHiddenDangerInfo);
		// appHiddenDangerInfo.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
		validRepeat(appHiddenDangerInfo);
		validParamFormat(appHiddenDangerInfo);
		return updateById(appHiddenDangerInfo);
	}

	@Override
	public IPage<HiddenDangerInfo> selectPage(Page page, HiddenDangerInfo appHiddenDangerInfo) {
		// appHiddenDangerInfo.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
		return baseMapper.selectPage(page, appHiddenDangerInfo);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteByIds(List<Long> idList) {
		return removeByIds(idList);
	}

	@Override
	public void export(HiddenDangerInfo appHiddenDangerInfo, HttpServletRequest request, HttpServletResponse response) {

		IPage<HiddenDangerInfo> page = selectPage(new Page(0, -1), appHiddenDangerInfo);
		List<HiddenDangerInfo> records = page.getRecords();
		List<HiddenDangerInfoVo> appHiddenDangerInfoVos = new ArrayList<>();
		for (HiddenDangerInfo expert : records) {
			// appHiddenDangerInfoVos.add(new HiddenDangerInfoVo(expert));
		}

		String keyValue = "名称:name,租户id:tenantId";
		String title = "HiddenDangerInfo导出数据";
		String fileName = title + ".xls";
		try {
			OutputStream outputStream = OutputStreamUtil.getOutputStream(request, response, fileName);
			ExcelTools.exportExcel(outputStream, keyValue, appHiddenDangerInfoVos, ExcelConstant.XLS, title);
			response.flushBuffer();
			outputStream.close();
		} catch (IOException e) {
			log.error("excel导出失败", e);
			throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
		} catch (Exception e) {
			log.error("excel导出失败", e);
			throw new RuntimeException("excel导出失败！" + e.getMessage());
		}
	}

	@Override
	public HiddenDangerInfo getOneById(Serializable id) {
		return baseMapper.getOneById(id);
	}

	/**
	 * 校验重复
	 */
	private void validRepeat(HiddenDangerInfo appHiddenDangerInfo) {
		QueryWrapper<HiddenDangerInfo> queryWrapper = new QueryWrapper<>();
		// queryWrapper.eq("name", appHiddenDangerInfo.getName());
		List<HiddenDangerInfo> list = baseMapper.selectList(queryWrapper);
		if (list.size() == 0) {
			return;
		}
		if (list.size() > 1) {
			throw new BusinessException("名称有重复");
		}
		if (ObjectUtils.isEmpty(appHiddenDangerInfo.getId())) {
			throw new BusinessException("名称已存在");
		}
		if (!appHiddenDangerInfo.getId().equals(list.get(0).getId())) {
			throw new BusinessException("名称已存在");
		}

	}

	/**
	 * 校验参数必填
	 */
	private void validParamRequired(HiddenDangerInfo appHiddenDangerInfo) {
		Assert.notNull(appHiddenDangerInfo, "参数为空");
		Assert.notNull(appHiddenDangerInfo.getStatus(), "隐患状态");
		Assert.notNull(appHiddenDangerInfo.getCheckAccountId(), "当前隐患记录id");

		if (appHiddenDangerInfo.getStatus() == 0) {
			// 待整改状态
			Assert.notNull(appHiddenDangerInfo.getRectifyResult(), "整改结果");
			Assert.notNull(appHiddenDangerInfo.getRectifyRemark(), "整改回复");
			Assert.isTrue(appHiddenDangerInfo.getRectifyRemark().length() <= 140, "回复字数过长");

		} else if (appHiddenDangerInfo.getStatus() == 1) {
			// 待复查状态
			Assert.notNull(appHiddenDangerInfo.getId(), "整改记录id");
			Assert.notNull(appHiddenDangerInfo.getCheckResult(), "复查结果");
			Assert.notNull(appHiddenDangerInfo.getCheckRemark(), "复查回复");
			Assert.isTrue(appHiddenDangerInfo.getCheckRemark().length() <= 140, "回复字数过长");
		}
		// Assert.isTrue(StringUtils.isNotBlank(appHiddenDangerInfo.getName()), "名称为空");
	}

	/**
	 * 校验参数格式
	 */
	private void validParamFormat(HiddenDangerInfo appHiddenDangerInfo) {
		
	}

	/**
	 * 发送消息
	 * 
	 * @param content 消息内容
	 * @param ownerId 消息接收人/所属人
	 */
	public void saveMessage(String title, String content, String ownerId, String linkId, Boolean isPushJG) {

		MessageCenter messageCenter = new MessageCenter();

		messageCenter.setTenantId(linkappUserContextProducer.getCurrent().getTenantId());
		messageCenter.setContent(content);
		messageCenter.setOwnerId(ownerId);
		messageCenter.setType(messageTypeEnum.DANGER.ordinal());
		messageCenter.setSelf(false);
		messageCenter.setStatus(0);
		messageCenter.setTitle(title);
		messageCenter.setCreateTime(new Date());
		messageCenter.setLinkId(linkId);

		// 根据隐患记录id获取隐患详细
		HiddenDangerDTO hiddenDangerDTO = new HiddenDangerDTO();
		hiddenDangerDTO.setId(linkId);
		//type = 1为隐患
		hiddenDangerDTO.setType(1);
		if(StringUtils.isBlank(messageCenter.getContent())){
			IPage<HiddenDangerDTO> iPage = hiddenDangerMapper.selectListByPage(new Page<>(0, 1), hiddenDangerDTO);

			if (iPage.getRecords().size() > 0) {

				hiddenDangerDTO = iPage.getRecords().get(0);
			}

			messageCenter.setContent(hiddenDangerDTO.getContent());
		}

		messageCenterService.saveOne(messageCenter);

		if(isPushJG){
			// 手机推送
			appSendMessageService
					.pushMessageToPhone(messageCenter.getId().toString(), model.SECURITY, type.MSG, ownerId, title,
							content);
		}

	}

	/**
	 * 扩展
	 * @param title 标题
	 * @param content 内容
	 * @param ownerId 所属人id
	 * @param hiddenDanger 隐患
	 * @param isPushJG 是否推送
	 */
	public void saveMessage(String title, String content, String ownerId, HiddenDanger hiddenDanger, Boolean isPushJG) {
		MessageCenter messageCenter = new MessageCenter();

		messageCenter.setTenantId(hiddenDanger.getTenantId());
		messageCenter.setContent(content);
		messageCenter.setOwnerId(ownerId);
		messageCenter.setType(messageTypeEnum.DANGER.ordinal());
		messageCenter.setSelf(false);
		messageCenter.setStatus(0);
		messageCenter.setTitle(title);
		messageCenter.setCreateTime(new Date());
		messageCenter.setLinkId(hiddenDanger.getId());

		// 根据隐患记录id获取隐患详细
		HiddenDangerDTO hiddenDangerDTO = new HiddenDangerDTO();
		hiddenDangerDTO.setId(hiddenDanger.getId());
		//type = 1为隐患
		hiddenDangerDTO.setType(1);
		if(StringUtils.isBlank(messageCenter.getContent())){
			IPage<HiddenDangerDTO> iPage = hiddenDangerMapper.selectListByPage(new Page<>(0, 1), hiddenDangerDTO);

			if (iPage.getRecords().size() > 0) {

				hiddenDangerDTO = iPage.getRecords().get(0);
			}

			messageCenter.setContent(hiddenDangerDTO.getContent());
		}

		messageCenterService.saveOne(messageCenter);

		if(isPushJG){
			// 手机推送
			appSendMessageService
					.pushMessageToPhone(messageCenter.getId().toString(), model.SECURITY, type.MSG, ownerId, title,
							content);
		}
	}
}
